/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == nullptr || head->next == nullptr)
            return head;

        ListNode* newhead = new ListNode(0);    // 创建一个头结点
        newhead->next = head;
        // 保存 4 个要动的结点
        ListNode* prev = newhead;
        ListNode* cur = prev->next;
        ListNode* next = cur->next;
        ListNode* nnext = next->next;

        while(cur && next)
        {
            // 两两结点交换
            prev->next = next;
            next->next = cur;
            cur->next = nnext;

            // 继续
            prev = cur;
            cur = prev->next;
            if(cur)
                next = cur->next;
            if(next)
                nnext = next->next;
        }
        cur = newhead->next;
        delete newhead;

        return cur;
    }
};